package com.xinchao.ck_mips.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;

import com.obs.services.ObsClient;
import com.obs.services.ObsConfiguration;
import com.obs.services.exception.ObsException;
import com.orhanobut.logger.Logger;
import com.xinchao.ck_mips.BuildConfig;
import com.xinchao.ck_mips.bean.SourceInfoBean;
import com.xinchao.ck_mips.bean.UpgradeBean;
import com.xinchao.ck_mips.constant.CK;
import com.xinchao.devicemanage.util.DeviceTool;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;


/**
 * Created by wq on 2019/4/23.
 */
public class FileUtils {
    private static final String remote_dir = "wifidata" + "/" + (new SimpleDateFormat("yyyyMMdd", Locale.getDefault())).format(new Date()) + "/";
    private static Map<File, String> maps;

    /**
     * 获取目录大小
     *
     * @param dirPath 目录路径
     * @return 文件大小
     */
    public static String getDirSize(String dirPath) {
        return getDirSize(getFileByPath(dirPath));
    }

    /**
     * 获取目录大小
     *
     * @param dir 目录
     * @return 文件大小
     */
    public static String getDirSize(File dir) {
        long len = getDirLength(dir);
        return len == -1 ? "" : byte2FitMemorySize(len);
    }

    /**
     * 返回节目文件路径
     * version/节目版本号/素材名称
     *
     * @param sourceBean
     * @return
     */
    public static String getProgramFilePath(SourceInfoBean sourceBean) {
        String url = sourceBean.getUrl();
        String filename = url.substring(url.lastIndexOf("/") + 1);
        return CK.VERSION_DIRS_PATH + File.separator + sourceBean.getProgramVersion() + File.separator + filename;
    }

    /**
     * 返回apk路径
     *
     * @param
     * @return
     */
    public static String getAPKFilePath(int versioncode) {
        return CK.APK_PATH + File.separator + versioncode + ".apk";
    }

    /**
     * 字节数转合适内存大小
     * <p>保留3位小数</p>
     *
     * @param byteNum 字节数
     * @return 合适内存大小
     */
    public static String byte2FitMemorySize(long byteNum) {
        if (byteNum < 0) {
            return "shouldn't be less than zero!";
        } else if (byteNum < ConstUtils.KB) {
            return String.format("%.3fB", byteNum + 0.0005);
        } else if (byteNum < ConstUtils.MB) {
            return String.format("%.3fKB", byteNum / ConstUtils.KB + 0.0005);
        } else if (byteNum < ConstUtils.GB) {
            return String.format("%.3fMB", byteNum / ConstUtils.MB + 0.0005);
        } else {
            return String.format("%.3fGB", byteNum / ConstUtils.GB + 0.0005);
        }
    }

    /**
     * 删除指定文件下的所有文件
     *
     * @param path
     */
    public static void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
            }
        }
    }

    /**
     * 删除文件夹
     *
     * @param folderPath
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath);
            String filePath = folderPath;
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据文件路径获取文件
     *
     * @param filePath 文件路径
     * @return 文件
     */
    public static File getFileByPath(String filePath) {
        return isSpace(filePath) ? null : new File(filePath);
    }

    /**
     * 检测本地文件是否有效
     *
     * @param filePath
     * @return
     */
    public static boolean isFileAvailable(String filePath) {
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            return true;
        }

        return false;
    }

    /**
     * 判断字符串是否为null或全为空格
     *
     * @param s 待校验字符串
     * @return {@code true}: null或全空格<br> {@code false}: 不为null且不全空格
     */
    public static boolean isSpace(String s) {
        return (s == null || s.trim().length() == 0);
    }

    /**
     * 获取目录长度
     *
     * @param dir 目录
     * @return 文件大小
     */
    public static long getDirLength(File dir) {
        if (!isDir(dir)) return -1;
        long len = 0;
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                if (file.isDirectory()) {
                    len += getDirLength(file);
                } else {
                    len += file.length();
                }
            }
        }
        return len;
    }

    /**
     * 判断是否是目录
     *
     * @param file 文件
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isDir(File file) {
        return isFileExists(file) && file.isDirectory();
    }

    /**
     * 判断文件是否存在
     *
     * @param file 文件
     * @return {@code true}: 存在<br>{@code false}: 不存在
     */
    public static boolean isFileExists(File file) {
        return file != null && file.exists();
    }

    /**
     * 保存正式环境token
     *
     * @param token
     */
    public static void saveToken(String token) {
        FileOutputStream fileOutputStream = null;
        try {
            File file = new File(CK.TOKEN_PATH);
            if (file.exists() && file.isFile()) {
                file.delete();
            }

            if (!file.exists()) {
                file.createNewFile();
            }

            fileOutputStream = new FileOutputStream(file);
            byte[] bt = token.getBytes();
            fileOutputStream.write(bt);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建token文件
     */
    public static void saveTokenFile() {
        FileOutputStream fileOutputStream = null;
        try {
            if (BuildConfig.DEBUG_LOG) {
                //测试
                if (!TextUtils.isEmpty(ShareUtil.getInstance().getString(CK.SP_DEBUG_TOKEN, ""))) {
                    String token = ShareUtil.getInstance().getString(CK.SP_DEBUG_TOKEN, "");
                    File file = new File(CK.TOKEN_DEBUG_PATH);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    fileOutputStream = new FileOutputStream(file);
                    byte[] bt = token.getBytes();
                    fileOutputStream.write(bt);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } else {
                //正式
                if (!TextUtils.isEmpty(ShareUtil.getInstance().getString(CK.SP_TOKEN, ""))) {
                    String token = ShareUtil.getInstance().getString(CK.SP_TOKEN, "");
                    File file = new File(CK.TOKEN_PATH);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    fileOutputStream = new FileOutputStream(file);
                    byte[] bt = token.getBytes();
                    fileOutputStream.write(bt);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 保持测试环境token
     *
     * @param token
     */
    public static void saveDebugToken(String token) {
        FileOutputStream fileOutputStream = null;
        try {
            File file = new File(CK.TOKEN_DEBUG_PATH);
            if (file.exists() && file.isFile()) {
                file.delete();
            }

            if (!file.exists()) {
                file.createNewFile();
            }

            fileOutputStream = new FileOutputStream(file);
            byte[] bt = token.getBytes();
            fileOutputStream.write(bt);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除token文件
     */
    public static void delToken() {
        try {
            File file = new File(CK.TOKEN_PATH);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除token文件
     */
    public static void delDebugToken() {
        try {
            File file = new File(CK.TOKEN_DEBUG_PATH);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取token
     *
     * @return
     */
    public static String getToken() {
        try {
            File file = new File(CK.TOKEN_PATH);
            if (!file.exists()) {
                return "";
            }

            if (file.exists() && file.isFile()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                StringBuffer info = new StringBuffer();
                String message = null;
                while ((message = br.readLine()) != null) {
                    info.append(message);
                }

                br.close();
                isr.close();

                return info.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * 获取测试环境token值
     *
     * @return
     */
    public static String getDebugToken() {
        try {
            File file = new File(CK.TOKEN_DEBUG_PATH);
            if (!file.exists()) {
                return "";
            }

            if (file.exists() && file.isFile()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                StringBuffer info = new StringBuffer();
                String message = null;
                while ((message = br.readLine()) != null) {
                    info.append(message);
                }

                br.close();
                isr.close();

                return info.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    public static void setDefaultJPGIntoCache(Context mContext, String dirPath, String[] jpgPath) {
        try {
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            InputStream is = null;
            for (int i = 0; i < jpgPath.length; i++) {
                File file = new File(jpgPath[i]);
                if (file.exists()) {
                    file.delete();
                    file.createNewFile();
                }
                if (i == 0) {
                    is = mContext.getResources().getAssets().open("splash_landscape_img.png");
                } else if (i == 1) {
                    is = mContext.getResources().getAssets().open("splash_default_img.png");
                }

                FileOutputStream fileOutputStream = new FileOutputStream(file);
                int length = 0;
                byte[] bt = new byte[1024];
                while ((length = is.read(bt)) != -1) {
                    fileOutputStream.write(bt, 0, length);
                }
                fileOutputStream.flush();
                fileOutputStream.close();
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取视屏播放时长
     *
     * @param videoPath
     * @return
     */
    public static long getVideoTime(String videoPath) {
        android.media.MediaMetadataRetriever mmr = new android.media.MediaMetadataRetriever();
        try {
            mmr.setDataSource(videoPath);
            String duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
            return Long.parseLong(duration);
        } catch (Exception e) {
            Logger.t("video time").e("解析视频文件长度出错:" + videoPath);
            return 0;
        }
    }

    public static boolean isAppInstall(Context mContext) {
        boolean isInstall = false;
        try {
            PackageManager packageManager = mContext.getPackageManager();
            List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);
            for (int i = 0; i < packageInfoList.size(); i++) {
                if (packageInfoList.get(i).packageName.equals("com.sypro")) {
                    isInstall = true;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return isInstall;
    }

    public static void deleteAPK(Context mContext) {
        Intent intent = new Intent(Intent.ACTION_DELETE);
        intent.setData(Uri.parse("package:com.sypro"));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    //获取当前时间
    public static String getWifiProbeName() {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// HH:mm:ss
            Date date = new Date(System.currentTimeMillis());
            return DeviceTool.getDeviceCode() + "_" + simpleDateFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * 上传多个文件
     *
     * @param files
     * @return
     */
    public static Map<File, String> uploadFile2Cloud(File[] files) {
        if (maps == null) {
            maps = new HashMap<>();
        }
        uploadFile2Cloud(0, files);
        return maps;
    }

    /**
     * 递归上传
     *
     * @param index
     * @param files
     */
    private static void uploadFile2Cloud(int index, File[] files) {
        if (files == null || files.length == 0)
            return;
        if (index >= files.length) {
            return;
        }
        String url = uploadFile2Cloud(files[index]);
        if (!TextUtils.isEmpty(url)) {
            maps.put(files[index], url);
        }
        uploadFile2Cloud(index + 1, files);
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public static String uploadFile2Cloud(File file) {
        if (file == null)
            return "";
        return uploadFile2CloudSingle(file.getAbsolutePath());
    }

    /**
     * 上传小文件
     *
     * @param fileName
     * @return
     */
    public static String uploadFile2CloudSingle(String fileName) {
        if (!isFileExist(fileName)) {
            return "";
        }
        // 创建ObsConfiguration配置类实例
        ObsConfiguration config = new ObsConfiguration();
        config.setEndPoint(BuildConfig.HUAWEI_OBS_ENDPOINT);
        config.setHttpsOnly(true);

        // 创建ObsClient实例
        ObsClient obsClient = new ObsClient(BuildConfig.HUAWEI_OBS_AK, BuildConfig.HUAWEI_OBS_SK, config);
        String remote_name = getFileName(fileName);

        try {
            // 进行断点续传上传
            obsClient.putObject(BuildConfig.HUAWEI_OBS_BUCKET_NAME_WIFI, remote_dir + remote_name, new File(fileName));
            return "https://" + BuildConfig.HUAWEI_OBS_BUCKET_NAME_WIFI + "." + BuildConfig.HUAWEI_OBS_ENDPOINT + "/" + remote_dir + remote_name;
        } catch (ObsException e) {
            // 发生异常时可再次调用断点续传上传接口进行重新上传
            StringBuffer buffer = new StringBuffer().append("Response Code:" + e.getResponseCode())
                    .append("\n\n")
                    .append("Error Message:" + e.getErrorMessage())
                    .append("\n\n")
                    .append("Error Code:" + e.getErrorCode())
                    .append("\n\n")
                    .append("Request ID:" + e.getErrorRequestId())
                    .append("\n\n")
                    .append("Host ID:" + e.getErrorHostId());
            Logger.t("upload-file").e(buffer.toString());
        } finally {
            // 关闭obsClient
            try {
                obsClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Logger.t("upload-file").e("close");
        }
        return "";
    }

    public static boolean isFileExist(String filePath) {
        boolean result = false;
        File file = new File(filePath);
        if (file != null && file.exists() && file.isFile()) {
            result = true;
        }
        return result;
    }

    /**
     * 获取文件名
     *
     * @param fileName
     * @return
     */
    private static String getFileName(String fileName) {
        int index = fileName.lastIndexOf("/");
        if (index == -1)
            return System.currentTimeMillis() + ".log";
        return fileName.substring(index + 1, fileName.length());
    }

    public static void startWifiProbe() {

    }

    /**
     * 是否合法ip地址
     *
     * @param s
     * @return
     */
    public static boolean checkIP(String s) {
        return s.matches("((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))");
    }

    /**
     * 是否合法端口
     *
     * @param s
     * @return
     */
    public static boolean checkPort(String s) {
        return s.matches("^([1-9]?\\d|[1-5]\\d{4}|6[0-4]\\d{3}|65[0-4]\\d{2}|655[0-2]\\d|6553[0-5])$");
    }

}
